package com.cq.base.dialog

import android.app.Dialog
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import com.cq.base.R

/**
 * 作者: CQ
 * 日期: 2021-10-25
 * 说明:
 */
class InputDialog : Dialog {
    private var mContext : Context

    init {
        window!!.decorView.setPadding(50, 0, 50, 0)
        val attributes = window!!.attributes
        attributes.width = ViewGroup.LayoutParams.MATCH_PARENT
        attributes.height = ViewGroup.LayoutParams.WRAP_CONTENT
        attributes.gravity = Gravity.CENTER
        window!!.attributes = attributes
    }

    constructor(context : Context) : super(context) {
        mContext = context
    }

    constructor(context : Context, themeResId : Int) : super(context, themeResId) {
        mContext = context
    }

    /**
     * 使用builder模式
     */
    class Builder(context : Context) {
        private var context : Context? = context
        private var input : String? = null
        private var isCancelable = true
        private var isCancelOutside = true

        /**
         * 设置提示信息
         */
        fun setMessage(message : String?) : Builder {
            this.input = message
            return this
        }

        /**
         * 设置是否可以按返回键取消
         */
        fun setCancelable(isCancelable : Boolean) : Builder {
            this.isCancelable = isCancelable
            return this
        }

        /**
         * 设置是否可以取消
         */
        fun setCancelOutside(isCancelOutside : Boolean) : Builder {
            this.isCancelOutside = isCancelOutside
            return this
        }

        fun create() : InputDialog {
            val inflater = LayoutInflater.from(context)
            val view : View = inflater.inflate(R.layout.dialog_input, null)
            val editText = view.findViewById<EditText>(R.id.input)
            val inputDialog = InputDialog(context!!, R.style.InputDialog)
            if (input != null)
                editText.setText(input)
            inputDialog.setContentView(view)
            // dialog弹出后会点击屏幕或物理返回键，dialog不消失
            inputDialog.setCancelable(isCancelable)
            // 点击Dialog以外的区域时Dialog消失
            inputDialog.setCanceledOnTouchOutside(isCancelOutside)

            view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
                inputDialog.cancel()
                doBackCall(editText.text.toString())
            }

            view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
                inputDialog.cancel()
            }
            return inputDialog
        }

        private var doBackCall : (msg : String) -> Unit = {}

        fun doOnBackCall(doBackCall : (msg : String) -> Unit) : Builder {
            this.doBackCall = doBackCall
            return this
        }
    }
}